package com.example.myfirstgame;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.os.Bundle;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.example.myfirstgame.controller.CollisionListener;
import com.example.myfirstgame.controller.GameObject;
import com.example.myfirstgame.controller.GameObjectContainer;
import com.example.myfirstgame.helper.Coordinate;
import com.example.myfirstgame.helper.DataInstance;
import com.example.myfirstgame.helper.FramePerSecondViewer;
import com.example.myfirstgame.helper.Raster;
import com.example.myfirstgame.helper.Rasterizer;
import com.example.myfirstgame.model.Car;
import com.example.myfirstgame.model.ParkingLots;
import com.example.myfirstgame.model.TrafficLight;
import com.example.myfirstgame.model.Tree;

@SuppressLint("WrongCall")
public class DrawCaptureActivity extends Activity implements OnTouchListener {

	OurView v;
	Bitmap ball;
	Bitmap pointer;
	float x, y;
	Paint linePaint;
	Paint textPaint;
	GameObjectContainer mGameObjectContainer;
	Car sportsCar;
	Car standardCar;
	TrafficLight trfLght;
	Tree tree;
	ParkingLots parkingLots;
	boolean collision = false;
	CollisionListener myCollisionListener = new CollisionListener(this);
	long counter = 0;
	String fps = "";
	Matrix matrix = null;
	FramePerSecondViewer fpsViewer;
	Raster mRaster;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.draw_capture);
		v = new OurView(this, this);
		v.setOnTouchListener(this);
		DataInstance.getInstance().setAppContext(getApplicationContext());
		
		Display display = getWindowManager().getDefaultDisplay();
		Rasterizer lRasterizer = new Rasterizer(display.getHeight(), display.getWidth());
		lRasterizer.initRastering(1.67f, 100);
		mRaster = lRasterizer.generateRaster();
		
		mGameObjectContainer = new GameObjectContainer(myCollisionListener);
		sportsCar = new Car(Car.TYPE_SPORTSCAR, this.getApplicationContext(),mRaster.getRasterPoint(50f, 10f));
		standardCar = new Car(Car.TYPE_STANDARD, this.getApplicationContext(),mRaster.getRasterPoint(50f, 30f));
		tree = new Tree(Tree.TYPE_TREE_01, this.getApplicationContext(),mRaster.getRasterPoint(80f, 50f));
		trfLght = new TrafficLight(TrafficLight.TYPE_TRAFFIC_LIGHT_01, this.getApplicationContext(),mRaster.getRasterPoint(75f, 75f));
		parkingLots = new ParkingLots(ParkingLots.TYPE_01, this.getApplicationContext(),mRaster.getRasterPoint(10f, 0f),2,3);
		
		mGameObjectContainer.add(sportsCar);
		mGameObjectContainer.add(standardCar);
		mGameObjectContainer.add(trfLght);
		mGameObjectContainer.add(tree);
		mGameObjectContainer.add(parkingLots.getAllIncludedGameObjects());
		
		x = y = 0;
		matrix = new Matrix();
		linePaint = new Paint();
		linePaint.setColor(Color.BLACK);
		linePaint.setStrokeWidth(2);
		textPaint = new Paint();
		textPaint.setColor(Color.BLUE);
		textPaint.setTextSize(25);
		textPaint.setTextAlign(Align.LEFT);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setContentView(v);
	}

	@Override
	protected void onPause() {
		super.onPause();
		v.pause();
	}

	protected void onResume() {
		super.onResume();
		v.resume();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add("+");
		menu.add("-");
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		float newScaleFactor = DataInstance.getInstance().getGameObjectScalingFactor();
		if(item.getTitle().equals("+")){
			newScaleFactor *= 1.1f; 
			mGameObjectContainer.scaleAllGameObjects(newScaleFactor, mRaster.getmRasterSize());
		}else if(item.getTitle().equals("-")){
			newScaleFactor *= 0.9f; 
			mGameObjectContainer.scaleAllGameObjects(newScaleFactor, mRaster.getmRasterSize());
		}
		return super.onOptionsItemSelected(item);
	}
	

	public class OurView extends SurfaceView implements Runnable {
		Thread t = null;
		SurfaceHolder holder;
		boolean isItOK = false;
		Activity activity;

		public OurView(Context context, Activity _activity) {
			super(context);
			holder = getHolder();
			activity = _activity;
		}

		public void run() {
			while (isItOK == true) {

				try {
					Thread.sleep(25);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

				// perform canvas drawing
				if (!holder.getSurface().isValid()) {
					continue;
				}
				Canvas c = holder.lockCanvas();
				FramePerSecondViewer.update();
				onDraw(c);
				holder.unlockCanvasAndPost(c);
			}
		}

		public void onDraw(Canvas c) {
			boolean curCollisionState = myCollisionListener.checkCollisionState();
			if(!collision && curCollisionState){
				activity.runOnUiThread(toastRunnable);
				collision = true;
			}
			collision = curCollisionState;
			c.drawARGB(255, 210, 210, 210);
			c.drawText(FramePerSecondViewer.getFps() + "/s", 50, 50, textPaint);
			drawLine(c, sportsCar.getDriveLine(), linePaint);
			drawLine(c, standardCar.getDriveLine(), linePaint);
			
			for (GameObject lGameObject: mGameObjectContainer.deliverSortedListForDrawing()){
				lGameObject.draw(c);
			}
			mRaster.draw(c);
//			for (RasterPoint pRP: mRaster.getRPList()){
//				pRP.draw(c);
//			}
			
		}

		public void pause() {
			isItOK = false;
			while (true) {
				try {
					t.join();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				break;
			}
			t = null;
		}

		public void resume() {
			isItOK = true;
			t = new Thread(this);
			t.start();
		}
	}

	public boolean onTouch(View v, MotionEvent me) {

		switch (me.getAction()) {
		case MotionEvent.ACTION_DOWN:
			x = me.getX();
			y = me.getY();
			sportsCar.listener(0, x, y);
			standardCar.listener(0, x, y);
			break;
		case MotionEvent.ACTION_UP:
			x = me.getX();
			y = me.getY();
			sportsCar.listener(2, x, y);
			standardCar.listener(2, x, y);
			break;
		case MotionEvent.ACTION_MOVE:
			x = me.getX();
			y = me.getY();
			sportsCar.listener(1, x, y);
			standardCar.listener(1, x, y);
			break;
		}
		return true;
	}

	private void drawLine(Canvas canvas, ArrayList<Coordinate> lineList,
			Paint paint) {
		if (lineList != null) {
			if (lineList.size() >=2){
			for (int i = 0; i <= lineList.size() - 2; i++) {
				Coordinate start = lineList.get(i);
				Coordinate stop = lineList.get(i + 1);
				// (float startX, float startY, float stopX, float stopY,
				canvas.drawLine(start.getX(), start.getY(), stop.getX(),
						stop.getY(), paint);
			}}
		}
	}
	Runnable toastRunnable = new Runnable() {
		
		@Override
		public void run() {
			Toast.makeText(getApplicationContext(), "Collition", Toast.LENGTH_SHORT).show();
		}
	};
}